package com.mt.restaurant.service.sale.impl;

import com.mt.restaurant.dao.sale.MenuMaterialRelationShipDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import com.mt.restaurant.dto.sale.MenuMaterialRelationShipHandleDto;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.sale.MenuMaterialRelationShip;
import com.mt.restaurant.service.sale.MenuMaterialRelationShipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class MenuMaterialRelationShipServiceBean extends BaseService implements MenuMaterialRelationShipService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private MenuMaterialRelationShipDao menuMaterialRelationShipDao;

	@Resource
	private RedisTemplate<String, List<MenuMaterialRelationShip>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询菜谱材料关系集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findMenuMaterialRelationShips(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindMenuMaterialRelationShips(pageDTO);
		List<MenuMaterialRelationShip> menuMaterialRelationShipDTOS = this.menuMaterialRelationShipDao.findMenuMaterialRelationShips(pageDTO);
		Long totalCount = this.menuMaterialRelationShipDao.findMenuMaterialRelationShipTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(menuMaterialRelationShipDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部菜谱材料关系集合
	 *
	 */
	@Override
	public List<MenuMaterialRelationShip> findAllMenuMaterialRelationShips(){
		return this.menuMaterialRelationShipDao.findAllMenuMaterialRelationShips();
	}

	/**
	 * 查询所有菜谱材料关系集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<MenuMaterialRelationShip> findAllMenuMaterialRelationShipsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllMenuMaterialRelationShipsWithIdName();
		return this.menuMaterialRelationShipDao.findAllMenuMaterialRelationShipsWithIdName();
	}

	/**
	 * 根据名称查询菜谱材料关系集合(只提取ID 和 Name)
	 *
	 * @param menuMaterialRelationShipName 名称
	 */
	@Override
	public List<MenuMaterialRelationShip> findMenuMaterialRelationShipsWithIdNameByName(String menuMaterialRelationShipName){
		//TODO:请在此校验参数的合法性
		this.validateFindMenuMaterialRelationShipsWithIdNameByName(menuMaterialRelationShipName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:MenuMaterialRelationShip_where_menuMaterialRelationShipName_" + menuMaterialRelationShipName);
		List<MenuMaterialRelationShip> menuMaterialRelationShips = new ArrayList<>();
		if (keys.isEmpty()) {
		menuMaterialRelationShips = this.menuMaterialRelationShipDao.findMenuMaterialRelationShipsWithIdNameByName(menuMaterialRelationShipName);
		redisTemplate.opsForValue().set("searchData:MenuMaterialRelationShip_where_menuMaterialRelationShipName_" + menuMaterialRelationShipName, menuMaterialRelationShips, 30, TimeUnit.DAYS);
		} else {
		menuMaterialRelationShips = redisTemplate.opsForValue().get("searchData:MenuMaterialRelationShip_where_menuMaterialRelationShipName_" + menuMaterialRelationShipName);
		}
		return menuMaterialRelationShips;
	}

	/**
	 * 根据ID查询指定的菜谱材料关系(只提取ID 和 Name)
	 *
	 * @param menuMaterialRelationShipId Id
	 */
	@Override
	public MenuMaterialRelationShip findMenuMaterialRelationShipsWithIdNameById(Long menuMaterialRelationShipId){
		//TODO:请在此校验参数的合法性
		this.validateFindMenuMaterialRelationShipsWithIdNameById(menuMaterialRelationShipId);
		return this.menuMaterialRelationShipDao.findMenuMaterialRelationShipsWithIdNameById(menuMaterialRelationShipId);
	}

	/**
	 * 根据ID查询指定的菜谱材料关系
	 *
	 * @param menuMaterialRelationShipId Id
	 */
	@Override
	public MenuMaterialRelationShip findMenuMaterialRelationShip(Long menuMaterialRelationShipId){
		//TODO:请在此校验参数的合法性
		this.validateFindMenuMaterialRelationShip(menuMaterialRelationShipId);
		return this.menuMaterialRelationShipDao.findMenuMaterialRelationShip(menuMaterialRelationShipId);
	}

	/**
	 * 根据ID查询指定的菜谱材料关系(包含外键)
	 *
	 * @param menuMaterialRelationShipId Id
	 */
	@Override
	public MenuMaterialRelationShip findMenuMaterialRelationShipWithForeignName(Long menuMaterialRelationShipId){
		//TODO:请在此校验参数的合法性
		this.validateFindMenuMaterialRelationShipWithForeignName(menuMaterialRelationShipId);
		return this.menuMaterialRelationShipDao.findMenuMaterialRelationShipWithForeignName(menuMaterialRelationShipId);
	}

	/**
	 * 新增菜谱材料关系
	 *
	 * @param menuMaterialRelationShip 实体对象
	 */
	@Override
	public MenuMaterialRelationShip saveMenuMaterialRelationShip(MenuMaterialRelationShip menuMaterialRelationShip){
		//TODO:请在此校验参数的合法性
		this.validateSaveMenuMaterialRelationShip(menuMaterialRelationShip);
		//TODO:填充公共参数
		this.setSavePulicColumns(menuMaterialRelationShip);
		Long rows = this.menuMaterialRelationShipDao.saveMenuMaterialRelationShip(menuMaterialRelationShip);
		if(rows != 1)
		{
			String error = "新增保存菜谱材料关系出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return menuMaterialRelationShip;
	}

	/**
	 * 更新菜谱材料关系
	 *
	 * @param menuMaterialRelationShip 实体对象
	 */
	@Override
	public MenuMaterialRelationShip updateMenuMaterialRelationShip(MenuMaterialRelationShip menuMaterialRelationShip){
		//TODO:请在此校验参数的合法性
		this.validateUpdateMenuMaterialRelationShip(menuMaterialRelationShip);
		Long rows = this.menuMaterialRelationShipDao.updateMenuMaterialRelationShip(menuMaterialRelationShip);
		if(rows != 1)
		{
			String error = "修改保存菜谱材料关系出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return menuMaterialRelationShip;
	}

	/**
	 * 根据ID删除菜谱材料关系
	 *
	 * @param menuMaterialRelationShipId ID
	 */
	@Override
	public void deleteMenuMaterialRelationShip(Long menuMaterialRelationShipId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteMenuMaterialRelationShip(menuMaterialRelationShipId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(MenuMaterialRelationShip.class, menuMaterialRelationShipId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.menuMaterialRelationShipDao.deleteMenuMaterialRelationShip(menuMaterialRelationShipId);
		if(rows != 1){
			String error = "删除菜谱材料关系出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	@Override
	public void batchSave(List<MenuMaterialRelationShip> menuMaterialRelationShips) {
		this.menuMaterialRelationShipDao.batchSave(menuMaterialRelationShips);
	}

	@Override
	public void batchHandle(MenuMaterialRelationShipHandleDto menuMaterialRelationShipHandleDto) {
		List<MenuMaterialRelationShip> insertRecords = menuMaterialRelationShipHandleDto.getInsertRecords();
		if(!insertRecords.isEmpty()) {
			this.menuMaterialRelationShipDao.batchSave(insertRecords);
		}
		List<MenuMaterialRelationShip> updateRecords = menuMaterialRelationShipHandleDto.getUpdateRecords();
		for (MenuMaterialRelationShip menuMaterialRelationShip:updateRecords
			 ) {
			this.menuMaterialRelationShipDao.updateMenuMaterialRelationShip(menuMaterialRelationShip);
		};
		List<MenuMaterialRelationShip> removeRecords = menuMaterialRelationShipHandleDto.getRemoveRecords();
		for (MenuMaterialRelationShip menuMaterialRelationShip:removeRecords
		) {
			this.menuMaterialRelationShipDao.deleteMenuMaterialRelationShip(menuMaterialRelationShip.getEid());
		};
	}
	//TODO:---------------验证-------------------

	private void validateFindMenuMaterialRelationShips(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateFindMenuMaterialRelationShipsWithIdNameByName(String menuMaterialRelationShipName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}


	private void validateFindAllMenuMaterialRelationShipsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateFindMenuMaterialRelationShipsWithIdNameById(Long menuMaterialRelationShipId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateFindMenuMaterialRelationShip(Long menuMaterialRelationShipId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateFindMenuMaterialRelationShipWithForeignName(Long menuMaterialRelationShipId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateSaveMenuMaterialRelationShip(MenuMaterialRelationShip menuMaterialRelationShip) {
	//不为空判断
	if (menuMaterialRelationShip.getEid() != null || menuMaterialRelationShip.getCreatorId() != null || menuMaterialRelationShip.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateUpdateMenuMaterialRelationShip(MenuMaterialRelationShip menuMaterialRelationShip) {
	//不为空判断
	if (menuMaterialRelationShip.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.menuMaterialRelationShipDao.findMenuMaterialRelationShipTotalCount(PageDTO.create(MenuMaterialRelationShip.FIELD_ID, menuMaterialRelationShip.getEid())) == 0) {
	throw new BusinessException("修改的菜谱材料关系 " + menuMaterialRelationShip.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	private void validateDeleteMenuMaterialRelationShip(Long menuMaterialRelationShipId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMenuMaterialRelationShip()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
